package nl.ypmits.utils.as3.data.remoting {
	import nl.ypmits.utils.as3.data.remoting.event.RemotingManagerEvent;

	import flash.events.Event;
	import flash.events.EventDispatcher;

	/**
	 * @author Dave Lenz
	 */
	public class RemotingManager extends EventDispatcher {

		private static var _instance : RemotingManager;
		
		private var data : Array = [];

		
		public function RemotingManager() {
			_instance = this;
		}

		
		public static function get instance() : RemotingManager {
			if (!_instance) {
				_instance = new RemotingManager( );
			}
			return _instance;
		}
		
		
		public function load( gateway : String, classpath : String, arg : String ) : void {
			var r : Remoting = new Remoting( gateway, classpath, arg );
			r.addEventListener( Event.COMPLETE, done );
		}
		
		
		public function retrieveData( classpath : String ) : * {
			for (var i : int = 0; i < data.length; i++) {
				if( classpath == data[i][0]) {
					return data[i][1];
					break;
				}
			}
			return null;
		}

		
		private function done( e : Event ) : void {
			data.push( [ Remoting( e.currentTarget ).classpath, Remoting( e.currentTarget ) ] );
			e.stopImmediatePropagation();
			
			var evt : RemotingManagerEvent = new RemotingManagerEvent( RemotingManagerEvent.COMPLETE );
			evt.remotingobject = Remoting( e.currentTarget );
			dispatchEvent( evt );
		}
	}
}
